package com.atguigu.gmall.pay.service.impl;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;

import com.alipay.api.AlipayConfig;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.mq.MqConst;
import com.atguigu.gmall.mq.to.OrderPayedSkuDetailTo;
import com.atguigu.gmall.mq.to.OrderPayedSuccessMessageTo;
import com.atguigu.gmall.pay.config.AppAliPayConfig;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {


        @Autowired
        AlipayClient alipayClient;

        @Autowired
        AppAliPayConfig alipayConfig;

        @Autowired
        OrderFeignClient orderFeignClient;

        @Autowired
        RabbitTemplate rabbitTemplate;




        /**
         * vo收集到页面支付请求的核心信息
         * @param vo
         * @return
         */
        @Override
        public String payOrder(PayParamsVo vo) throws Exception {

            //1、创建一个支付请求,time_expire
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
            alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());


            //2、设置支付请求的请求体详情
            String json = new ObjectMapper().writeValueAsString(vo);
            alipayRequest.setBizContent(json);

            //3、调用支付宝的支付功能
            String result = alipayClient.pageExecute(alipayRequest).getBody();


            //result //代表的是支付宝返回的二维码支付页


            //返回支付宝的二维码支付页
            return result;
        }

    /**
     * 检查订单是否支付
     * @param outTradeNo
     * @return
     */
    @Override
    public Boolean queryOrderStatus(String outTradeNo) throws JsonProcessingException, AlipayApiException {
        //1、设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();


        //请二选一设置
        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",outTradeNo);
        String asString = new ObjectMapper().writeValueAsString(map);

        alipayRequest.setBizContent(asString);

        //请求
        AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
        if("10000".equals(response.getCode()) && response.getTradeStatus().equals("TRADE_SUCCESS")){
            //支付成功
            return true;

        }

        return false;
    }

    @Override
    public void sendPaySuccessMessage(String out_trade_no) throws JsonProcessingException {


        //TODO 2、给队列发送的内容; JSON串
        OrderInfo orderInfo = orderFeignClient.getOrderInfoWithDetailsByOutTradeNo(out_trade_no);
        //商品详情
        List<OrderPayedSkuDetailTo> details = new ArrayList<>();
        //1、准备mq消息内容，封装订单信息
        OrderPayedSuccessMessageTo message = new OrderPayedSuccessMessageTo();
        BeanUtils.copyProperties(orderInfo,message);

        message.setOrderId(orderInfo.getId());
        //拿到第一个商品名字
        message.setOrderBody(orderInfo.getOrderDetailList().get(0).getSkuName());
        message.setPaymentWay("2");//在线支付

        //2、封装订单的所有商品信息

        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            OrderPayedSkuDetailTo detailTo = new OrderPayedSkuDetailTo();
            BeanUtils.copyProperties(detail,detailTo);
            details.add(detailTo);
        }

        message.setDetail(details);

        //TODO 1、队列名： queue.ware.stock  需要知道哪个交换机用哪个路由键绑定了这个对象
        String string = new ObjectMapper().writeValueAsString(message);

        //给库存系统发送了消息
        rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_WARE_STOCK,MqConst.ROUTING_WARE_STOCK,string);
        // 队列名： MqConst.QUEUE_WARE_STOCK
        //         * 交换机名： MqConst.EXCHANGE_DIRECT_WARE_STOCK
        //         * 路由键： MqConst.ROUTING_WARE_STOCK
        //         * @RabbitListener(bindings = 声明的关系)  也会自动创建出队列交换机和绑定关系
        //         * @Bean也能创建出来
        /**
         * @RabbitListener(bindings = @QueueBinding(
         *             value = @Queue(value = MqConst.QUEUE_WARE_STOCK, durable = "true"),
         *             exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_STOCK, type = ExchangeTypes.DIRECT, durable = "true"),
         *             key = {MqConst.ROUTING_WARE_STOCK}
         *     ))
         */


    }
}
